package io.renren.modules.sys.service.impl;

import java.util.Arrays;
import java.util.Date;
import java.util.List;
import java.util.Map;

import org.apache.commons.lang.ArrayUtils;
import org.apache.commons.lang.RandomStringUtils;
import org.apache.commons.lang.StringUtils;
import org.apache.shiro.crypto.hash.Sha256Hash;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.baomidou.mybatisplus.plugins.Page;
import com.baomidou.mybatisplus.service.impl.ServiceImpl;
import com.github.pagehelper.PageHelper;

import io.renren.common.constant.Code;
import io.renren.common.exception.BizException;
import io.renren.common.utils.Constant;
import io.renren.common.utils.Query;
import io.renren.common.utils.ShiroUtils;
import io.renren.modules.sys.dao.UserDao;
import io.renren.modules.sys.entity.User;
import io.renren.modules.sys.service.RoleService;
import io.renren.modules.sys.service.UserRoleService;
import io.renren.modules.sys.service.UserService;


/**
 * 系统用户
 * 
 * @author chenshun
 * @email sunlightcs@gmail.com
 * @date 2016年9月18日 上午9:46:09
 */
@Service
public class UserServiceImpl extends ServiceImpl<UserDao, User> implements UserService {
	@Autowired
	private UserRoleService sysUserRoleService;
	@Autowired
	private RoleService sysRoleService;

	@Override
	public List<User> queryPage(Map<String, Object> params) {
		String username = (String)params.get("username");
		Long createUserId = (Long)params.get("createUserId");
		if(params.get("page") != null && params.get("limit") != null){
			PageHelper.startPage(Integer.parseInt((String)params.get("page")), Integer.parseInt((String)params.get("limit")));
		}
//		Page<User> page = this.selectPage(
//			new Query<User>(params).getPage(),
//			new EntityWrapper<User>()
//				.like(StringUtils.isNotBlank(username),"username", username)
//				.eq(createUserId != null,"create_user_id", createUserId)
//		);
		
		List<User> list = this.selectList(
				new EntityWrapper<User>()
					.like(StringUtils.isNotBlank(username),"username", username)
					.eq(createUserId != null,"create_user_id", createUserId)
			);

		return list;
	}

	@Override
	public List<String> queryAllPerms(String userId) {
		return baseMapper.queryAllPerms(userId);
	}

	@Override
	public List<String> queryAllMenuId(String userId) {
		return baseMapper.queryAllMenuId(userId);
	}

	@Override
	public User queryByUserName(String username) {
		return baseMapper.queryByUserName(username);
	}

	@Override
	@Transactional
	public void save(User user) {
		user.setCreateTime(new Date());
		//sha256加密
		String salt = RandomStringUtils.randomAlphanumeric(20);
		user.setPassword(new Sha256Hash(user.getPassword(), salt).toHex());
		user.setSalt(salt);
		this.insert(user);
		
		//检查角色是否越权
		checkRole(user);
		
		//保存用户与角色关系
		sysUserRoleService.saveOrUpdate(user.getUserId(), user.getRoleIdList());
	}

	@Override
	@Transactional
	public void update(User user) {
		if(StringUtils.isBlank(user.getPassword())){
			user.setPassword(null);
		}else{
			user.setPassword(new Sha256Hash(user.getPassword(), user.getSalt()).toHex());
		}
		this.updateById(user);
		
		//检查角色是否越权
		checkRole(user);
		
		//保存用户与角色关系
		sysUserRoleService.saveOrUpdate(user.getUserId(), user.getRoleIdList());
	}

	@Override
	public void deleteBatch(String[] userId) {
		if(ArrayUtils.contains(userId, 1L)){
			throw new BizException(Code.COODE_USER_O1,"系统管理员不能删除");
		}
		
		if(ArrayUtils.contains(userId, ShiroUtils.getUserId())){
			throw new BizException(Code.COODE_USER_O2,"当前用户不能删除");
		}
		this.deleteBatchIds(Arrays.asList(userId));
	}

	@Override
	public boolean updatePassword(String userId, String password, String newPassword) {
		User userEntity = new User();
		userEntity.setPassword(newPassword);
		return this.update(userEntity,
				new EntityWrapper<User>().eq("user_id", userId).eq("password", password));
	}
	
	/**
	 * 检查角色是否越权
	 */
	private void checkRole(User user){
		if(user.getRoleIdList() == null || user.getRoleIdList().size() == 0){
			return;
		}
		//如果不是超级管理员，则需要判断用户的角色是否自己创建
		if(Constant.SUPER_ADMIN.equals(user.getCreateUserId() )){
			return ;
		}
		
		//查询用户创建的角色列表
		List<String> roleIdList = sysRoleService.queryRoleIdList(user.getCreateUserId());

		//判断是否越权
		if(!roleIdList.containsAll(user.getRoleIdList())){
			throw new BizException("新增用户所选角色，不是本人创建");
		}
	}
}
